define(['jquery',"bbcare","comm/datatable/datatable","bld/app/comm/comm","bld/app/course/courseEdit.servers","bld/app/course/courseEdit.ui"],function($,$bb,$datatable,$bldcomm,$servers,$ui) {
    var courseEdit = {};
    var obj = {};

    /**
     * 模态框小类回调函数2
     */
    var ajaxSmallClassCallBack02 = function(data,datas){
        datas.smallClass = data.medCatalogInfos;
        datas.status = "update";
        modalUi(datas,datas.medicines[datas.index]);
    }

    /**
     * 选择搜索出的某一个药品
     */
    var selectMedicineName = function() {
        var datas = $(this).data("datas");
        $("#inputQuery").hide();
        datas.index = $(this).index();
        var params = {
            "medCatalogInfo":{
                "classId":datas.medicines[datas.index].class_id
            }
        };
        $servers.ajaxMedicineSmallClass(params,ajaxSmallClassCallBack02,datas);
    }

    /**
     * 选择药品名称回调函数
     */
    var ajaxSelectCallBack = function(data,datas) {
        if( data.rows.length > 0 ){
            datas.medicines = data.rows;
            $ui.selectCallBack({
                "id": "inputQuery",
                "list": data.rows
            });
            $("#inputQuery").show();
            $("#inputQuery .query_item").unbind("click");
            $("#inputQuery .query_item").data("datas",datas);
            $("#inputQuery .query_item").click(selectMedicineName);
        }else{
            $("#inputQuery").hide();
        }
    }

    /**
     * 查询药品名称回调函数
     */
    var onSelectByName = function() {
        var datas = $(this).data("datas");
        var medicineName = $("#medicineName").val();
        var params = {
            "medicineName": medicineName,
            "medicineType":"1"
        };
        $servers.ajaxSelect(params,ajaxSelectCallBack,datas);
    }
    
    /**
     * 模态框小类回调函数
     */
    var ajaxSmallClass = function(data) {
        $ui.smallClass({
            "dom": $("#catalogId"),
            "list": data.medCatalogInfos
        })
    }

    /**
     * 大类改变时触发
     */
    var onChangeBigClass = function(){
        var classId = $(this).val();
        var params = {
            "medCatalogInfo":{
                "classId":classId
            }
        };
        $servers.ajaxMedicineSmallClass(params,ajaxSmallClass);
    }

    /**
     * 添加药品回调函数
    */
    var ajaxAddCallBack = function(data,datas) {
        $('.' + datas.className).modal('hide');
        obj.courseVersion = data.courseVersion;
        obj.status = "0";
        courseDetail();
    }

    /**
     * 添加药品
     */
    var onAdd = function() {
        var datas = $(this).data("datas");
        var id = $(this).attr("data-id");
        var medicineId = $(this).attr("data-medicineId");
        var medicineName = $.trim($("#medicineName").val());
        var classId = $("#classId").val();
        var catalogId = $("#catalogId").val();
        var frequencyDay = $("#frequencyDay").val();
        var frequencyTime = $("#frequencyTime").val();
        var calcuMethod = $("#calcuMethod").val();
        var medicineDose = $.trim($("#medicineDose").val());
        var medUnitId = $("#medUnitId").val();
        var medicineType = $("#medicineType").val();
        var character = $("#character").val();
        var indication = $("#indication").val();
        var adverseReaction = $("#adverseReaction").val();
        var taboo = $("#taboo").val();
        var considerations = $("#considerations").val();
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var channelId = $bb.getChannelId();
        var dataObj = {"medicineName":medicineName,"frequencyDay":frequencyDay,"frequencyTime":frequencyTime,"medicineDose":medicineDose};
        if( $bldcomm.validateMedicine(dataObj) ){
            var params = {
                "oprInfo":{
                    "opCode": "2058",
                    "opType": "3",
                    "opNote": "【" + doctorName + "】医生向疗程库中添加药品【" + medicineName + "】",
                    "channelType": "2",
                    "channelId": channelId
                },
                "medicineInfo":{
                    "medicineName": medicineName,
                    "classId": classId,
                    "catalogId": catalogId,
                    "id":medicineId
                },
                "medSkuInfo":{
                    "medicineDose": medicineDose,
                    "calcuMethod": calcuMethod,
                    "frequencyDay": frequencyDay,
                    "frequencyTime": frequencyTime,
                    "useUnitId": medUnitId,
                    "medicineType": medicineType,
                    "medUnitId": medUnitId,
                    "character": character,
                    "indication": indication,
                    "adverseReaction": adverseReaction,
                    "taboo": taboo,
                    "considerations": considerations,
                    "id":id,
                },
                "courseId":obj.id,
                "courseVersion":obj.courseVersion,
                "seqNo":$('#datatable thead tr th').length - 1,
            };
            $servers.ajaxAdd(params,ajaxAddCallBack,datas);
        }
    }

    /**
     * 修改药品成功后的回调函数
     */
    var ajaxUpdateCallBack = function(data,datas) {
        $('.' + datas.className).modal('hide');
        obj.courseVersion = data.medSkuId.courseVersion;
        obj.status = "0";
        courseDetail();
    }

    /**
     * 修改
     */
    var onUpdate = function() {
        var datas = $(this).data('datas');
        var medicineName = $.trim($("#medicineName").val());
        var frequencyDay = $("#frequencyDay").val();
        var frequencyTime = $("#frequencyTime").val();
        var calcuMethod = $("#calcuMethod").val();
        var medicineDose = $.trim($("#medicineDose").val());
        var medUnitId = $("#medUnitId").val();
        var medicineType = $("#medicineType").val();
        var character = $("#character").val();
        var indication = $("#indication").val();
        var adverseReaction = $("#adverseReaction").val();
        var taboo = $("#taboo").val();
        var considerations = $("#considerations").val();
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var channelId = $bb.getChannelId();
        if ( !medicineName || medicineName == '' ) {
            $bb.toastShow('药品名称不能为空');
            return;
        }
        if ( !frequencyDay || frequencyDay == '' ) {
            $bb.toastShow('服用周期天数不能为空');
            return;
        }
        if ( !frequencyTime || frequencyTime == '' ) {
            $bb.toastShow('服用周期次数不能为空');
            return;
        }
        if ( !medicineDose || medicineDose == '' ) {
            $bb.toastShow('药品剂量不能为空');
            return;
        }
        var params = {
            "oprInfo":{
                "opCode": "2057",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生修改药品【" + medicineName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "courseMedicineInfo":{
                "courseId": obj.id,
                "courseVersion": obj.courseVersion,
                "seqNo": datas.seqNo,
                "medicineId": datas.medSkuInfo.medicine_id,
                "medSkuId": datas.medSkuInfo.id,
                "medicineName": medicineName,
            },
            "medSkuInfo":{
                "medicineDose": medicineDose,
                "calcuMethod": calcuMethod,
                "frequencyDay": frequencyDay,
                "frequencyTime": frequencyTime,
                "useUnitId": medUnitId,
                "medicineType": medicineType,
                "medUnitId": medUnitId,
                "character": character,
                "indication": indication,
                "adverseReaction": adverseReaction,
                "taboo": taboo,
                "considerations": considerations
            }
        };
        $servers.ajaxUpdateCourseMedicine(params,ajaxUpdateCallBack,datas);
    }

    /**
     * 重置
     */
    var onReset = function(){
        var datas = $(this).data("datas");
        var obj = {};
        obj.status = "add";
        modalUi(datas,obj);
    }

    /**
     * 模态框初始化
     */
    var modalUi = function(datas,obj){
        var options = {
            "dom": $("." + datas.className + " .modal-body"),
            "status":datas.status,
            "units":datas.units,
            "bigClass":datas.bigClass,
            "smallClass":datas.smallClass,
        };
        datas.status == "readonly" ? $.extend(options,datas.medSkuInfo) : $.extend(options,obj);
        $ui.add(options);
        $("." + datas.className).modal("show");
        // 大类改变时触发
        $("#classId").unbind("change");
        $("#classId").change(onChangeBigClass);
        if( datas.status == "readonly" ){
            // 修改 (暂时不做)
            /*$("#update").unbind("click");
            $("#update").data('datas',datas);
            $("#update").bind("click",onUpdate);*/
        }else{
            // 模态框内的药名搜索
            $("#medicineName").unbind("input propertychange");
            $("#medicineName").data("datas",datas);
            $("#medicineName").bind("input propertychange", onSelectByName);
            // 添加药品并应用给疗程
            $("#add").unbind("click");
            $("#add").data("datas",datas);
            $("#add").bind("click",onAdd);
            // 重置
            $("#reset").unbind("click");
            $("#reset").data("datas",datas);
            $("#reset").bind("click", onReset);
        }
    }

    /**
     * 请求大类成功后的回调函数
     */
    var ajaxSmallClassCallBack = function(data,datas){
        datas.smallClass = data.medCatalogInfos;
        datas.className = "courseEditModal";
        var tit = datas.status == "readonly" ? "药品详情":"药品添加页";
        $bb.modal({
            "className": datas.className,
            "tit": tit,
        }, function() {
            modalUi(datas);
        });
    }

    /**
     * 模态框大类回调函数
     */
    var ajaxBigClass = function(data,datas) {
        datas.bigClass = data.data;
        if( datas.medSkuInfo && datas.medSkuInfo.class_id ){
            var classId = datas.medSkuInfo.class_id;
            datas.status = "readonly";
        }else{
            var classId = data.data[0].id;
            datas.status = "add";
        }
        var params = {
            "medCatalogInfo":{
                "classId":classId
            }
        };
        $servers.ajaxMedicineSmallClass(params,ajaxSmallClassCallBack,datas);
    }

    /**
     * 查询药品单位回调函数
     */
    var ajaxQueryUnit = function(data,datas) {
        datas.units = data.medUnits;
        $servers.ajaxMedicineBigClass(ajaxBigClass,datas);
    }

    /**
     * 点击添加事件
     */
    var onAddClick = function() {
        var datas = {};
        $servers.ajaxQueryUnit(ajaxQueryUnit,datas);
    }

    /**
     * 获取药品信息
     */
    var medUpdateCallback = function(currMedicine,seqNo) {
        var datas = {"seqNo":seqNo};
        datas.medSkuInfo = {
            "medicine_name":currMedicine.medicineName,
            "class_id":currMedicine.classId,
            "parentId":currMedicine.parentId,
            "frequency_day":currMedicine.frequencyDay,
            "frequency_time":currMedicine.frequencyTime,
            "calcu_method":currMedicine.calcuMethod,
            "medicine_dose":currMedicine.medicineDose,
            "med_unit_id":currMedicine.medUnitId,
            "medicine_type":currMedicine.medicineType,
            "character":currMedicine.character,
            "indication":currMedicine.indication,
            "adverse_reaction":currMedicine.adverseReaction,
            "taboo":currMedicine.taboo,
            "considerations":currMedicine.considerations,
            "medicine_id":currMedicine.medicineId,
            "id":currMedicine.medSkuId,
        };
        $servers.ajaxQueryUnit(ajaxQueryUnit,datas);
    }

    /**
     * 修改药物
     */
    var onUpdateMed = function() {
        var medicines = $(this).data("datas").medicines;
        var seqNo = $(this).parents("th").attr("data-seqNo");
        var medSkuId = $(this).attr("data-medSkuId");
        var currMedicine = $servers.getCurrMedicineByMedSkuId(medicines,medSkuId);
        medUpdateCallback(currMedicine,seqNo);
    }

    /**
     * 删除疗程库下某个疗程中的某种药品成功后的回调函数
     */
    var ajaxRemoveCourseMedicine = function(data) {
        $bb.toastShow("删除成功！");
        obj.courseVersion = data.courseVersion;
        obj.status = "0";
        courseDetail();
    }

    /**
     * 请求删除疗程中的药品
     */
    var confirmDeleteMed = function(params) {
        $servers.ajaxRemoveCourseMedicine(params,ajaxRemoveCourseMedicine);
    }

    /**
     * 删除药品
     */
    var deleteMed = function() {
        var medicineId = $(this).attr('data-medicineId');
        var seqNo = parseInt($(this).parent("th").attr('data-seqNo'));
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var medicineName = $(this).parent().children('div').eq(1).children('span').html();
        var channelId = $bb.getChannelId();
        var params = {
            "oprInfo":{
                "opCode": "2061",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生删除疗程库中药品【" + medicineName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "courseId": obj.id,
            "courseVersion": obj.courseVersion,
            "medicineId": medicineId,
            "seqNo": seqNo,
        };
        $bb.toastConfirmShow(confirmDeleteMed, params, "确认是否删除？")
    }

    /**
     * 发布疗程
     */
    var publishCourse = function(data){
        if( data.medicines.length > 0 && !$.isEmptyObject(data.courseDataInfos) ){
            $("#release").html('<button type="button" class="btn btn-warning" id="releaseBtn">发布疗程</button>');
            // 发布疗程
            $("#releaseBtn").unbind('click');
            $("#releaseBtn").click(releaseCourse);
        }
    }

    /**
     * 前后移动药物
     */
    var ajaxMoveMedicine = function(data) {
        $bb.toastShow("移动药物成功！");
        obj.courseVersion = data.courseVersion;
        obj.status = "0";
        courseDetail();
    }

    /**
     * 移动药物
     */
    var onMoveMed = function(){
        var moveDirection = $(this).data("moveDirection");
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var channelId = $bb.getChannelId();
        var medicineName = $(this).parent().find('.course-list-medicineName span').html();
        var seqNo = parseInt($(this).parent("th").attr('data-seqNo'));
        var params = {
            "oprInfo":{
                "opCode": "2056",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生移动药物【" + medicineName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "courseData":{
                "courseId": obj.id,
                "courseVersion": obj.courseVersion,
                "seqNo": seqNo,
                "moveDirection": moveDirection
            }
        };
        $servers.ajaxMoveMedicine(params,ajaxMoveMedicine);
    }

    /**
     * 添加天数成功后的回调函数
     */
    var ajaxIncreaseDay = function(data) {
        $bb.toastShow('给该疗程添加天数成功！');
        obj.courseVersion = data.courseVersion;
        obj.status = "0";
        courseDetail();
    }

    /**
     * 添加天数
     */
    var increaseDay = function() {
        if ( $('#datatable thead tr th').length == 2 ) {
            $bb.toastShow('请先新增药物');
            return;
        }
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var channelId = $bb.getChannelId();
        var seqDay = $('#datatable tbody tr:first-child td').html() == '暂无数据' ? 1 : $('#datatable tbody tr').length;
        var params = {
            "oprInfo":{
                "opCode": "2059",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生给【" + obj.courseName + "】疗程添加第【" + seqDay + "】天",
                "channelType": "2",
                "channelId": channelId
            },
            "courseId":obj.id,
            "courseVersion":obj.courseVersion,
            "seqDay":seqDay
        };
        $servers.ajaxIncreaseDay(params,ajaxIncreaseDay);
    }

    /**
     * 删除接口成功后的回调函数
     */
    var ajaxReduceDay = function(data) {
        $bb.toastShow("删除成功！");
        obj.courseVersion = data.courseVersion;
        obj.status = "0";
        courseDetail();
    }

    /**
     * 请求删除接口
     */
    var confirmReduceDay = function(params) {
        $servers.ajaxReduceDay(params,ajaxReduceDay);
    }

    /**
     * 删除天数
     */
    var reduceDay = function() {
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var channelId = $bb.getChannelId();
        var seqDay = parseInt($(this).parents("tr").attr('data-index'));
        var params = {
            "oprInfo":{
                "opCode": "2060",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生删除疗程【" + obj.courseName + "】中的【" + seqDay + "】天",
                "channelType": "2",
                "channelId": channelId
            },
            "courseId":obj.id,
            "courseVersion":obj.courseVersion,
            "seqDay":seqDay,
        };
        $bb.toastConfirmShow(confirmReduceDay,params,"是否确认删除第" + seqDay + "天的用药数据");
    }

    /**
     * 调整药品剂量成功后的回调函数回调函数
     */
    var ajaxChangeMedicineDose = function(data) {
        $bb.toastShow("保存成功！");
        obj.courseVersion = data.courseVersion;
        obj.status = "0";
        courseDetail();
    }

    /**
     * 单元格设置value
     */
    var onSetValueCell = function(){
        var value = parseFloat( $(this).val() );
        if( value < 0 ) {
            $bb.toastShow('请输入大于0的数字');
        }else{
            var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
            var channelId = $bb.getChannelId();
            var datas = $(this).data("datas");
            var params = {
                "oprInfo":{
                    "opCode": "2062",
                    "opType": "3",
                    "opNote": "【" + doctorName + "】医生给【" + obj.courseName + "】疗程调整第【" + datas.seqDay + "】天药品【" + datas.currMedicine.medicineName + "】的剂量",
                    "channelType": "2",
                    "channelId": channelId
                },
                "courseId":obj.id,
                "courseVersion":obj.courseVersion,
                "medicineId":datas.currMedicine.medicineId,
                "seqDay":datas.seqDay,
                "medicineDose":value,
            };
            $servers.ajaxChangeMedicineDose(params,ajaxChangeMedicineDose);
        }
    }

    /**
     * 给疗程库中的疗程调整某天某种药品的剂量
     */
    var onChangeMedicineDose = function(){
        if( $(this).children('input').length ) return false;
        var medicines = $(this).data("medicines");
        var seqDay = parseInt( $(this).parent("tr").attr("data-index") );
        var medicineId = $(this).attr("data-medicineId");
        var currMedicine = $servers.getCurrMedicine(medicines,medicineId);
        var initValue = $(this).attr("data-value");
        if( initValue == 0 || !initValue ) initValue == currMedicine.medicineDose;
        $(this).html('<input class="text-center" type="number" min="0">');
        var $input = $(this).children();
        $input.focus().val(initValue).unbind("blur");
        $input.data("datas",{"currMedicine":currMedicine,"seqDay":seqDay});
        $input.blur(onSetValueCell);
    }

    /**
     * 查询疗程详情成功后的回调函数
     */
    var ajaxViewCourse = function(data) {
        // 是否存在“发布疗程”按钮
        if( obj.status == "0" ) publishCourse(data);
        var arr = $servers.handleData(data);
        $ui.tableHead({
            "dom": $("#datatable thead"),
            "list": data.medicines
        });
        $ui.tableContent({
            "dom": $("#datatable tbody"),
            "list": arr
        });
        // 新增药物
        $('#datatable thead tr th:last-child').unbind('click');
        $('#datatable thead tr th:last-child').click(onAddClick);
        // 删除药物
        $('.delBtn').unbind('click');
        $('.delBtn').click(deleteMed);
        // 移动药物
        $(".course-list-upBtn").unbind("click");
        $(".course-list-upBtn").data("moveDirection","up");
        $(".course-list-upBtn").click(onMoveMed);
        $(".course-list-downBtn").unbind("click");
        $(".course-list-downBtn").data("moveDirection","down");
        $(".course-list-downBtn").click(onMoveMed);
        // 修改药物
        $(".course-list-medicineName").unbind("click");
        $(".course-list-medicineName").data("datas",{"medicines":data.medicines});
        $(".course-list-medicineName").click(onUpdateMed);
        // 点击添加天数的按钮
        $('#increaseDay').unbind('click');
        $('#increaseDay').click(increaseDay);
        // 删除疗程中的某一天
        $('.delDay').unbind('click');
        $('.delDay').click(reduceDay);
        // 添加、修改用药剂量
        var $rows = $("#datatable tbody").children();
        $rows.each(function(i,e){
            // 没有数据返回、最后一行【添加按钮】屏蔽
            if( $('#datatable tbody tr:first-child td').html() == '暂无数据' || i == $rows.length - 1 ) return true;
            // 其他情况
            $($(e).children()).each(function(index,element){
                if( index == 0 || index == $($(e).children()).length - 1 ) return true;
                $(element).unbind("click");
                $(element).data("medicines",data.medicines);
                $(element).bind("click",onChangeMedicineDose);
            })
        });
    }
        
    /**
     * 发布疗程成功后的回调函数
     */
    var ajaxReleaseCourse = function(data) {
        $bb.toastShow('疗程发布成功',2000);
        setTimeout(function() {
            if( obj.source && obj.source.name ){
                $bb.openPage(obj.source.name,obj.source.params);
            }else{
                $bb.openPage('bld_courseList');
            }
        }, 2000);
    }

    /**
     * 确认发布疗程
     */
    var ajaxConfirmReleaseCourse = function(params) {
        $servers.ajaxReleaseCourse(params,ajaxReleaseCourse);
    }
    
    /**
     * 发布疗程
     */
    var releaseCourse = function() {
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var channelId = $bb.getChannelId();
        var params = {
            "oprInfo":{
                "opCode": "2054",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生发布疗程【" + obj.courseName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "courseId":obj.id,
            "courseVersion":obj.courseVersion,
        };
        $bb.toastConfirmShow(ajaxConfirmReleaseCourse,params,'确认将当前疗程进行发布么？');
    }

    /**
     * 修改疗程名称成功后的回调函数
     */
    var ajaxModifyCourseName = function(data,courseName){
        obj.courseName = courseName;
        $bb.toastShow(data);
    }

    /**
     * 修改疗程名称
     */
    var modifyCourseName = function() {
        var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
        var channelId = $bb.getChannelId();
        var courseName = $('#courseName').val();
        var params = {
            "oprInfo":{
                "opCode": "2055",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生修改疗程【" + obj.courseName + "】名称",
                "channelType": "2",
                "channelId": channelId
            },
            "course":{
                "id": obj.id,
                'new_version': obj.courseVersion,
                'courseName': courseName
            }
        };
        $servers.ajaxModifyCourseName(params,ajaxModifyCourseName,courseName);
    }

    /**
     * 请求疗程详情
     */
    var courseDetail = function(){
        // 请求疗程详情
        var params = {
            "courseId":obj.id,
            "courseVersion":obj.courseVersion,
        };
        $servers.ajaxViewCourse(params,ajaxViewCourse);
    }

    courseEdit.init = function() {
        obj = $bb.getPageParams();
        /* 修改疗程名称 */
        $("#courseName").val(obj.courseName);
        $("#saveBtn").unbind('click');
        $("#saveBtn").click(modifyCourseName);
        courseDetail();
    };

    return courseEdit;
});